// pages/my/register/register.js
Page({
  data: {
    registerForm: {
      phoneNumber: "",
      password: "",
      nickName: ""
    },
    loading: false
  },

  inputChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`registerForm.${field}`]: e.detail.value
    });
  },

  register() {
    const { phoneNumber, password, nickName } = this.data.registerForm;

    // 表单验证
    if (!phoneNumber || !password || !nickName) {
      wx.showToast({
        title: '请填写完整注册信息',
        icon: 'none'
      });
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    // 调用注册API
    this.registerToServer(phoneNumber, password, nickName)
     .then(res => {
        this.handleRegisterSuccess(res);
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });
        wx.navigateBack(); // 注册成功后返回上一页
      })
     .catch(err => {
        wx.showToast({
          title: err.message || '注册失败',
          icon: 'none'
        });
      })
     .finally(() => {
        this.setData({ loading: false });
      });
  },

  registerToServer(phoneNumber, password, nickName) {
    return new Promise((resolve, reject) => {
      // 模拟注册验证
      if (phoneNumber === '18296995790') {
        // 模拟成功响应
        setTimeout(() => {
          resolve({
            code: 200,
            msg: '注册成功',
            data: {
              id: 1,
              phoneNumber: '18296995790',
              nickName: nickName || '张角',
              avatarUrl: '/static/images/avatar/avatar.png',
              token: 'mock_token_' + Date.now(),
              createTime: new Date().toISOString()
            }
          });
        }, 500); // 模拟网络延迟
      } else {
        // 模拟失败响应
        setTimeout(() => {
          reject(new Error('注册失败，请稍后再试'));
        }, 300);
      }
    });
  },

  handleRegisterSuccess(res) {
    // 存储用户信息和token
    wx.setStorageSync('userInfo', res.data);
    wx.setStorageSync('token', res.data.token);
  },
  
  // 添加返回上一页的方法
  navigateBack() {
    wx.navigateBack();
  }
});